<!-- 多张上传 -->
<template>
    <div class="wrap-upload">
        <el-upload class="photo-uploader" :class="{ limited: uploadLimited }" ref="upload" :action="domain" :data="uploadData" list-type="picture-card" :file-list="uploadShowFileList" :limit="limitNum" :before-upload="beforeUpload" :on-success="uploadSuccess" :on-error="uploadError" :on-exceed="uploadExceed" :on-preview="uploadPreview" :on-remove="uploadRemove" multiple :disabled="disabled">
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">
                <span v-if="showType">请上传JPG/PNG格式</span>
                <span v-if="showSize"> {{ limitSize }}M</span>
                <span v-if="showLimit">，最多可上传{{ limitNum }}张</span>
            </div>
        </el-upload>
        <!-- 图片预览 -->
        <el-dialog title="图片预览" :visible.sync="dialogVisible" append-to-body>
            <img width="100%" :src="previewUrl" alt="" />
        </el-dialog>
    </div>
</template>

<script>
import uploadMixin from './mixin.js';
import { genNonDuplicateID, getFileName } from '@/utils/index.js';
export default {
    name: 'uploadPhotoList',
    mixins: [uploadMixin],
    props: {
        // 是否禁用
        disabled: {
            type: Boolean,
            default: false
        },
        // 对应的表单键名
        formKey: {
            required: true,
            type: String
        },
        // 上传后的图片
        uploadedUrl: {
            type: String,
            default: ''
        },
        // 是否展示提示-上传数量
        showLimit: {
            type: Boolean,
            default: true
        },
        // 限制上传数量
        limitNum: {
            type: Number,
            default: 5
        },
        // 是否展示提示-上传大小
        showSize: {
            type: Boolean,
            default: true
        },
        // 限制上传大小
        limitSize: {
            type: Number,
            default: 5
        },
        // 是否展示提示-上传类型
        showType: {
            type: Boolean,
            default: true
        },
    },
    data() {
        return {
            // 预览框
            dialogVisible: false,
            // 预览图片链接
            previewUrl: '',
            // 上传的图片列表 {name: '',url: ''}
            uploadShowFileList: [],
            // 上传是否达到限制
            uploadLimited: false
        }
    },
    methods: {
        // 图片上传前
        beforeUpload(file) {
            const isImage = file.type.includes("image");
            const isLimitSize = file.size / 1024 / 1024 < this.limitSize;
            if (!isImage) {
                this.$message_tip('上传图片只能是 JPG/PNG 格式!', 'error')
            }
            if (!isLimitSize) {
                this.$message_tip(`上传图片大小不能超过 ${this.limitSize}MB!`, 'error')
            }
            this.uploadData.key = genNonDuplicateID() + '|' + file.name
            return isImage && isLimitSize;
        },
        // 图片上传成功
        uploadSuccess(res, file, fileList) {
            let uploadFileList = fileList.map(item => {
                if (item.hasOwnProperty('response')) {
                    return `${this.qiniuUrl}/${item.response.key}`
                } else {
                    return item.url
                }
            })
            this.$emit('update-form', this.formKey, uploadFileList.join(','))
        },
        // 图片超出
        uploadExceed(files, fileList) {
            this.$message_tip(`最多可上传${this.limitNum}张图片`, 'error')
        },
        // 图片上传失败
        uploadError(err, file) {
            this.$message_tip('图片上传失败,请稍后重试！', 'error')
        },
        // 删除图片
        uploadRemove(file, fileList) {
            let uploadFileList = fileList.map(item => {
                if (item.hasOwnProperty('response')) {
                    return `${this.qiniuUrl}/${item.response.key}`
                } else {
                    return item.url
                }
            })
            this.$emit('update-form', this.formKey, uploadFileList.join(','))
        },
        // 上传图片预览
        uploadPreview(file) {
            this.previewUrl = file.url;
            this.dialogVisible = true;
        }
    },
    mounted() {
        // 已上传图片回显
        if (!this.uploadedUrl) return
        this.uploadShowFileList = this.uploadedUrl.split(',').map(item => {
            return {
                name: getFileName(item),
                url: item
            }
        })
        this.uploadLimited = this.uploadShowFileList.length >= this.limitNum ? true : false
    },
    watch: {
        'uploadedUrl': function (newVal, oldVal) {
            // 组件已上传图片
            let uploadedList = newVal ? newVal.split(',') : []
            this.uploadLimited = uploadedList.length >= this.limitNum ? true : false
            // 组件中取出已上传图片
            let uploadFileList = this.$refs.upload.uploadFiles.map(item => {
                if (item.hasOwnProperty('response')) {
                    return `${this.qiniuUrl}/${item.response.key}`
                } else {
                    return item.url
                }
            })
            //  组件取出未预览的图片
            let unShowFileList = uploadedList.filter(item => {
                return uploadFileList.indexOf(item) === -1
            }).map(ele => {
                return {
                    name: getFileName(ele),
                    url: ele
                }
            })
            // 未预览图片展示到预览图中
            if (unShowFileList.length <= 0) return
            this.uploadShowFileList = this.uploadShowFileList.concat(unShowFileList)
        }
    }
}
</script>

<style lang="scss" scoped>
// 最大宽度与表单最宽初保持一致
.wrap-upload {
    width: 100%;
}

::v-deep {
    .photo-uploader {
        .el-upload-list {
            .el-upload-list__item {
                width: 110px;
                height: 110px;
            }
        }
        .el-upload {
            width: 110px;
            height: 110px;
            line-height: 110px;
        }
        .el-upload:hover {
            border-color: #409eff;
        }

        &.limited {
            .el-upload--picture-card {
                display: none;
            }
        }
    }
}
</style>